/*
 * CUserManager.java Sep 18, 2012
 * Copyright(c) 20012-2015 by covidien
 * ALL Rights Reserved.
 */
package com.mvc.portal.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.base.model.UserNotice;
import com.mvc.framework.model.Auditable;
import com.mvc.portal.web.ExtendUserController;
import com.mvc.security.model.User;
import com.mvc.security.model.UserRole;
import com.mvc.security.service.UserManager;
import com.mvc.security.service.UserRoleManager;

/**
 * 
 * @author kevin
 * @version V1.0 Create Time: Sep 18, 2012
 */
@Service
public class CUserManager extends UserManager<User> {

	private static final int	DEFAULT_SUPPLIER_ROLE_ID	= 2;

	@Autowired
	private UserRoleManager	 userRoleManager;

	@Override
	public void save(User entity) {
		boolean addRoleFlag = false;
		if (null == entity.getObjectId()) {
			addRoleFlag = true;
		}
		super.save(entity);
		if (addRoleFlag) {
			UserRole userRole = new UserRole();
			if (entity.getType() == ExtendUserController.USER_SUPPLIER) {
				userRole.setRoleId(DEFAULT_SUPPLIER_ROLE_ID);
				userRole.setUserId(entity.getObjectId());
				userRoleManager.save(userRole);
			}
		}
	}

	public void deleteCUser(User user) {
		userRoleManager.deleteUserRoleByUserId(user.getObjectId());
		super.delete(user);
	}

	public List<User> getNoticeUsers(Integer type) {
		return searchBySql("select A from " + User.class.getName() + " A," + UserNotice.class.getName()
		        + " B where A.objectId = B.userId and B.type=? and A.recStatus=? and B.recStatus=?", new Object[] { type,
		        Auditable.REC_STATUS_VALID, Auditable.REC_STATUS_VALID });
	}
}
